import { login, logout, getInfo, loginWithSms } from '@/api/login'
// @ts-expect-error 不需要检测
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    isLogin: !!getToken(),
    userType: null,
    enterprise: null,
    currEnterprise: null,
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo: object) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            setToken(res.token)
            this.token = res.token
            this.isLogin = true
            resolve(true)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    loginSms(userInfo) {
      return new Promise((resolve, reject) => {
        loginWithSms(userInfo)
          .then((res) => {
            setToken(res.token)
            this.token = res.token
            this.isLogin = true
            resolve(true)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user
            const avatar =
              user.avatar == '' || user.avatar == null
                ? defAva
                : import.meta.env.VITE_APP_BASE_API + user.avatar

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.userType = user.userType
            this.name = user.nickName
            this.avatar = avatar
            this.enterprise = res.enterprise
            this.currEnterprise = res.enterprise
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    setCurrEnterprise(enterprise) {
      this.currEnterprise = enterprise
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = ''
            this.roles = []
            this.isLogin = false
            this.permissions = []
            localStorage.removeItem('currEnterprise')
            localStorage.clear()
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
  },
})

export default useUserStore
